home *** CD-ROM | disk | FTP | other *** search
Java Source | 2004-03-29 | 2.9 KB | 101 lines |
- import java.io.*;
- import javax.comm.*;
- import java.util.*;
-
- public class Com implements Runnable,SerialPortEventListener{
-
- //Dichiarazioni variabili
- static CommPortIdentifier portId;
- static Enumeration portList;
-
- SerialPort serialPort;
- Thread readThread;
- private InputStream serialInput;
-
- public static void main(String[] arg) throws Exception{
-
- //Richiede la lista delle porte disponibili
- portList=CommPortIdentifier.getPortIdentifiers();
-
- // Cerca fra le porte disponibili quella richiesta
- //finchΦ c'Φ ancora una porta nella lista
- while (portList.hasMoreElements()){
-
- //Prende un porta dalla lista
- portId=(CommPortIdentifier) portList.nextElement();
-
- // Controlla che la porta presa in considerazione sia
- //una porta seriale ed in particolare la COM1
- // Per le porte parallele utilizzare:
- //CommPortIdentifier.PORT_PARALLEL
- if ((portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
- && (portId.getName().equals("COM1"))){
-
- System.out.println("Porta trovata");
-
- new Com();
- break;
- }
- }
- }
-
-
- public Com() throws Exception{
-
- //Apre la porta con un timeout di 2sec (2000 msec)
- serialPort=(SerialPort) portId.open("RS232",2000);
-
- //Associa un evento all'input dalla porta
- serialPort.addEventListener(this);
- serialPort.notifyOnDataAvailable(true);
-
- //Setta i parametri della porta
- serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
- serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
-
- //Apre un canale di comunicazione
- serialInput=serialPort.getInputStream();
-
- System.out.println("Porta aperta");
-
- //Avvia il thread per l'ascolto
- readThread = new Thread(this);
- readThread.start();
-
- }
-
- //Thread in ascolto sulla tastiera
- public void run(){
-
- try{
-
- BufferedReader tastiera=new BufferedReader(new
- InputStreamReader(System.in));
-
- //Attesa comando quit
- while (!(tastiera.readLine().equals("quit")));
-
- //Chiusura porta
- serialPort.close();
- }
- catch (Exception e){
- System.out.println(e);}
- }
-
-
- public void serialEvent(SerialPortEvent event){
-
- //Verifica la presenza di dati nel buffer
- if (event.getEventType()==SerialPortEvent.DATA_AVAILABLE){
-
- try{
- //Legge i dati dal buffer (se presenti)
- while(serialInput.available()>0)
- System.out.print((char)serialInput.read());
- }
- catch (Exception e){
- System.out.println(e);
- }
- }
- }
- }